package com.leetcode.partition18;

import java.io.*;
import java.util.PriorityQueue;

/**
 * @author `RKC`
 * @date 2021/12/24 19:24
 */
public class LC1705吃苹果的最大数目 {

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
/*
5
1 2 3 5 2
3 2 1 4 2

6
3 1 1 0 0 2
3 1 1 0 0 2
 */
    public static void main(String[] args) throws IOException {
        String[] s = reader.readLine().split("\\s+");
        int n = Integer.parseInt(s[0]);
        int[] apples = new int[n], days = new int[n];
        s = reader.readLine().split("\\s+");
        for (int i = 0; i < n; i++) apples[i] = Integer.parseInt(s[i]);
        s = reader.readLine().split("\\s+");
        for (int i = 0; i < n; i++) days[i] = Integer.parseInt(s[i]);
        writer.write(String.valueOf(eatenApples(apples, days)));
        writer.flush();
    }

    public static int eatenApples(int[] apples, int[] days) {
        int n = apples.length, answer = 0, currTime = 0;
        //存放一个二元组（苹果数量，苹果过期的时间）
        PriorityQueue<int[]> heap = new PriorityQueue<>((o1, o2) -> Integer.compare(o1[1], o2[1]));
        for (int i = 0; i < n; i++, currTime++) {
            if (apples[i] != 0) heap.add(new int[]{apples[i], currTime + days[i]});
            //将苹果数量为0的和已经过期的苹果取出
            while (!heap.isEmpty() && (heap.peek()[0] == 0 || heap.peek()[1] <= currTime)) heap.poll();
            if (heap.isEmpty()) continue;
            //尽量先吃放久的苹果
            if (--heap.peek()[0] == 0) heap.poll();
            answer++;
        }
        //如果还剩有苹果，就还可以继续吃几天
        while (!heap.isEmpty()) {
            while (!heap.isEmpty() && (heap.peek()[0] == 0 || heap.peek()[1] <= currTime)) heap.poll();
            if (heap.isEmpty()) break;
            if (--heap.peek()[0] == 0) heap.poll();
            answer++;
            //紧接上面循环的时间线，时间增加放在后面
            currTime++;
        }
        return answer;
    }
}
